package com.lagou;

import com.mapper.Mapper;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;

public class MyMapperThread extends Thread {

    private Socket socket;

    private Mapper mapper;


    public MyMapperThread(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();

            //封装request和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(outputStream);

            HttpServlet httpServlet = null;
            String url = request.getUrl();
            List<Mapper.MappedHost> mappedHosts = mapper.getMappedHosts();
            for (Mapper.MappedHost mappedHost : mappedHosts) {
                if (mappedHost.getName().equals(request.getHostName())) {
                    List<Mapper.MappedContext> contexts = mappedHost.getContexts();
                    for (Mapper.MappedContext context : contexts) {
                        // /demo01/lagou
                        String[] split = url.trim().split("/");
                        if (context.getName().equals(split[1])) {
                            List<Mapper.MappedWrapper> exactWrappers = context.getExactWrappers();
                            for (Mapper.MappedWrapper exactWrapper : exactWrappers) {
                                if (exactWrapper.getUrl().equals("/" + split[2])) {
                                    httpServlet = (HttpServlet) exactWrapper.getServlet();
                                }
                            }
                        }
                    }
                }
            }
            if (httpServlet == null) {
                //静态资源
                response.outputHtml(url);
            } else {
                httpServlet.service(request, response);
            }
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
